<?php
namespace Emos\Db;

class MySql extends AbstractAdapter { 
    public function connect($params) {  
        $params = array(
            'host'      => 'localhost',
            'charset'   => 'utf8',
            'user'      => 'root',
            'password'  => ''
        ) + $params;
        
        $this->connection = @mysql_connect($params['host'], $params['user'], $params['password']);
        if(!@mysql_select_db($params['base'], $this->connection)) {
            throw new Exception("Can not connect to database '".$params['database']."'");            
        }        
        
        mysql_query('SET CHARACTER SET '.$params['charset'], $this->connection);        
    }    
    
    function selectQuery($sql) {
        $data = array();
		$res = mysql_query($sql, $this->connection);
        if(mysql_errno($this->connection) !== 0) {
            throw new Exception("SQL query error {$sql}", $sql);            
        }         
        
        while($rec = mysql_fetch_assoc($res)) {
            $data[] = $rec;
        }
        mysql_free_result($res);
        return $data;        
    }
    
    function execQuery($sql) {        
		mysql_query($sql, $this->connection);
        if(mysql_errno($this->connection) !== 0) {
            throw new Exception(mysql_error($this->connection), $sql);
        }
        return mysql_affected_rows($this->connection);
    }    
    
    function getInsertId() {
        return mysql_insert_id($this->connection);
    }
}
